﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;

namespace FileApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private System.Timers.Timer timer;

        private bool isRunning = false;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoginUser.InterfaceUrl = ConfigurationManager.AppSettings["InterfaceUrl"];
            LoginUser.FilePath = ConfigurationManager.AppSettings["FilePath"];
            LoginUser.CzId = Convert.ToInt32(ConfigurationManager.AppSettings["CZId"]);

            ReadFile();

            timer = new System.Timers.Timer(1000 * 30);
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        private async void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (isRunning) { return; }
            isRunning = true;
            await Upload(LoginUser.lastFile.LastTime);
            LoginUser.lastFile.LastTime = DateTime.Now;
        }

        public async Task Upload(DateTime? dt)
        {
            await Task.Run(() =>
             {
                 UploadPic("pic", $"{LoginUser.FilePath}\\pic", LoginUser.CzId, dt);
             });

            await Task.Run(() =>
             {
                 UploadPic("rwjl", $"{LoginUser.FilePath}\\pic", LoginUser.CzId, dt);
             });

            await Task.Run(() =>
             {
                 UploadPic("video", $"{LoginUser.FilePath}\\pic", LoginUser.CzId, dt);
             });
        }

        public async void UploadPic(string preDir, string dirPath, int czId, DateTime? lasttime)
        {
            try
            {
                //定义一个DirectoryInfo对象
                DirectoryInfo di = new DirectoryInfo(dirPath);
                List<FileView> list = new List<FileView>();

                //通过GetFiles方法,获取di目录中的所有文件的大小
                //foreach (FileInfo fi in di.GetFiles())
                //{
                //    list.Add(fi);
                //}

                foreach (var d in di.GetDirectories())
                {
                    foreach (FileInfo fi in d.GetFiles())
                    {
                        list.Add(new FileView() { DateTime = fi.LastWriteTime, Dir = d.Name, FullName = fi.FullName });
                    }
                }

                if (lasttime != null)
                {
                    list = list.Where(o => o.DateTime >= lasttime).ToList();
                }

                foreach (FileView fi in list)
                {
                    try
                    {
                        var buff = File.ReadAllBytes(fi.FullName);
                        UploadFileObj obj = new UploadFileObj()
                        {
                            FileName = Path.GetFileName(fi.FullName),
                            Dir = $"{preDir}/{fi.Dir}",
                            Base64 = Convert.ToBase64String(buff),
                            czId = czId
                        };
                        var succ = await APIService.UploadFile(obj);
                        if (!succ)
                        {
                            //noUploadFiles.Add(new noUploadFile() { Path = f, Dir = obj.Dir });
                        }
                    }
                    catch (Exception ex)
                    {
                        //noUploadFiles.Add(new noUploadFile() { Path = f, Dir = $"pic/{s}" });

                    }
                }
            }
            catch
            {

            }
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        private void ReadFile()
        {
            try
            {
                var json = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "lastFile.json", Encoding.UTF8);
                LoginUser.lastFile = Newtonsoft.Json.JsonConvert.DeserializeObject<LastFile>(json);
            }
            catch (Exception ex)
            {

            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(LoginUser.lastFile);
                File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "lastFile.json", json, Encoding.UTF8);
            }
            catch (Exception ex)
            {

            }
        }
    }
}
